import React, { useState, useEffect, useRef } from 'react';
import { Card } from '../components/Card';
import { Button } from '../components/Button';
import { audioManager } from '../utils/audio/audioManager';
import '../styles/theme.css';
import '../styles/animations.css';
import './App.css';

const phases = {
  inhale: { duration: 4, next: 'hold' },
  hold: { duration: 7, next: 'exhale' },
  exhale: { duration: 8, next: 'inhale' }
};

function App() {
  const [totalSeconds] = useState(300); // 5 minutes
  const [remainingSeconds, setRemainingSeconds] = useState(300);
  const [isRunning, setIsRunning] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [cycleCount, setCycleCount] = useState(0);
  const [currentPhase, setCurrentPhase] = useState('ready');
  const [breathingInterval, setBreathingInterval] = useState(null);
  const timerIntervalRef = useRef(null);

  useEffect(() => {
    return () => {
      if (timerIntervalRef.current) {
        clearInterval(timerIntervalRef.current);
      }
      if (breathingInterval) {
        clearTimeout(breathingInterval);
      }
    };
  }, [breathingInterval]);

  const startTimer = () => {
    if (timerIntervalRef.current) {
      clearInterval(timerIntervalRef.current);
    }

    timerIntervalRef.current = setInterval(() => {
      setRemainingSeconds(prev => {
        if (prev <= 1) {
          stopTimer();
          stopBreathingCycle();
          setCurrentPhase('complete');
          alert('Breathing exercise complete! Great job!');
          resetBreathing();
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  const stopTimer = () => {
    if (timerIntervalRef.current) {
      clearInterval(timerIntervalRef.current);
      timerIntervalRef.current = null;
    }
  };

  const performBreathingPhase = () => {
    if (!isRunning || remainingSeconds <= 0) return;

    const phase = phases[currentPhase];
    if (!phase) return;

    const timeoutId = setTimeout(() => {
      if (currentPhase === 'exhale') {
        setCycleCount(prev => prev + 1);
      }
      setCurrentPhase(phase.next);
      performBreathingPhase();
    }, phase.duration * 1000);

    setBreathingInterval(timeoutId);
  };

  const stopBreathingCycle = () => {
    if (breathingInterval) {
      clearTimeout(breathingInterval);
      setBreathingInterval(null);
    }
  };

  const startBreathing = () => {
    if (isPaused) {
      setIsPaused(false);
      startTimer();
      performBreathingPhase();
    } else {
      setIsRunning(true);
      setCurrentPhase('inhale');
      setCycleCount(0);
      startTimer();
      performBreathingPhase();
    }
  };

  const pauseBreathing = () => {
    setIsPaused(true);
    setIsRunning(false);
    stopTimer();
    stopBreathingCycle();
    setCurrentPhase('paused');
  };

  const resetBreathing = () => {
    setIsRunning(false);
    setIsPaused(false);
    setRemainingSeconds(totalSeconds);
    setCycleCount(0);
    setCurrentPhase('ready');
    stopTimer();
    stopBreathingCycle();
  };

  const getPhaseText = (phase) => {
    const texts = {
      ready: 'Ready',
      inhale: 'Breathe In',
      hold: 'Hold',
      exhale: 'Breathe Out',
      paused: 'Paused',
      complete: 'Complete!'
    };
    return texts[phase] || 'Ready';
  };

  const formatTime = (seconds) => {
    const minutes = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  const getActiveStep = () => {
    if (currentPhase === 'ready') return 1;
    if (currentPhase === 'inhale') return 2;
    if (currentPhase === 'hold') return 3;
    return 4;
  };

  return (
    <div className="breathing-app">
      <div className="breathing-header">
        <h1>🌬️ Breathing Exercise</h1>
        <button className="close-btn" onClick={() => window.close()} title="Close">×</button>
      </div>

      <div className="breathing-content">
        <div className="timer-section">
          <div className="timer-display">{formatTime(remainingSeconds)}</div>
          <div className="timer-controls">
            {!isRunning && (
              <Button onClick={startBreathing} variant="primary">Start</Button>
            )}
            {isRunning && (
              <Button onClick={pauseBreathing}>Pause</Button>
            )}
            <Button onClick={resetBreathing}>Reset</Button>
          </div>
        </div>

        <div className="breathing-circle-container">
          <div className={`breathing-circle ${currentPhase}`}>
            <div className="circle-inner">
              <span>{getPhaseText(currentPhase)}</span>
            </div>
          </div>
        </div>

        <div className="instructions-section">
          <h2>Instructions</h2>
          <div className="instructions-content">
            <div className={`instruction-step ${getActiveStep() === 1 ? 'active' : ''}`}>
              <h3>1. Find a comfortable position</h3>
              <p>Sit or lie down in a comfortable position. Close your eyes if you prefer.</p>
            </div>
            <div className={`instruction-step ${getActiveStep() === 2 ? 'active' : ''}`}>
              <h3>2. Follow the breathing pattern</h3>
              <p>Breathe in when the circle expands, breathe out when it contracts.</p>
            </div>
            <div className={`instruction-step ${getActiveStep() === 3 ? 'active' : ''}`}>
              <h3>3. 4-7-8 Technique</h3>
              <p>Inhale for 4 seconds, hold for 7 seconds, exhale for 8 seconds.</p>
            </div>
            <div className={`instruction-step ${getActiveStep() === 4 ? 'active' : ''}`}>
              <h3>4. Stay relaxed</h3>
              <p>Focus on your breath and let go of any tension. Repeat for 5 minutes.</p>
            </div>
          </div>
        </div>

        <div className="breathing-stats">
          <Card className="stat-item">
            <span className="stat-label">Cycles</span>
            <span className="stat-value">{cycleCount}</span>
          </Card>
          <Card className="stat-item">
            <span className="stat-label">Time Remaining</span>
            <span className="stat-value">{formatTime(remainingSeconds)}</span>
          </Card>
        </div>
      </div>
    </div>
  );
}

export default App;

